<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind" labelPosition="top" labelWidth="100">
			<uni-forms-item name="storage_id" label="所属仓库" required>
				<uni-data-select v-model="formData.storage_id" :localdata="storageRange"
					placeholder="请选择所属仓库"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="totalClassify_id" label="装备总类型" required>
				<uni-data-select v-model="formData.totalClassify_id" :localdata="totalClassifyRange"
					placeholder="请选择装备总类型"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="classify_id" label="装备分类" required>
				<uni-data-select v-model="formData.classify_id" :localdata="classifyRange"
					placeholder="请选择装备分类"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="firm_id" label="厂商" required>
				<uni-data-select v-model="formData.firm_id" :localdata="firmRange"
					placeholder="请选择装备厂商"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="equipmentName" label="装备名称" required>
				<uni-easyinput placeholder="装备名称" v-model="formData.equipmentName" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="imgFile" label="装备图片">
				<uni-file-picker return-type="object" v-model="formData.imgFile"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="equipmentParameter" label="装备参数">
				<uni-easyinput placeholder="装备参数(富文本)" v-model="formData.equipmentParameter"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="useMethod" label="使用方法">
				<uni-easyinput placeholder="使用方法(富文本)" v-model="formData.useMethod" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="remark" label="备注">
				<uni-easyinput placeholder="备注" v-model="formData.remark" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="storageState" label="在库状态">
				<switch @change="binddata('storageState', $event.detail.value)" :checked="formData.storageState">
				</switch>
			</uni-forms-item>
			<uni-forms-item name="equipmentStateInfo" label="装备状态信息" required>
				<uni-data-checkbox v-model="formData.equipmentStateInfo"
					:localdata="formOptions.equipmentStateInfo_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="purchaseTime" label="装备购入时间" required>
				<uni-datetime-picker return-type="timestamp" v-model="formData.purchaseTime"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="overInsuranceTime" label="装备过保时间" required>
				<uni-datetime-picker return-type="timestamp" v-model="formData.overInsuranceTime"></uni-datetime-picker>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/tab_EquipmentInfo.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'tab_EquipmentInfo';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"storage_id": "",
				"totalClassify_id": "",
				"classify_id": "",
				"firm_id": "",
				"equipmentName": "",
				"imgFile": null,
				"equipmentParameter": "",
				"useMethod": "",
				"remark": "",
				"storageState": true,
				"equipmentStateInfo": 0,
				"purchaseTime": null,
				"overInsuranceTime": null
			}
			return {
				formData,
				formOptions: {
					"equipmentStateInfo_localdata": [{
							"text": "建档阶段",
							"value": 0
						},
						{
							"text": "在库可用",
							"value": 1
						},
						{
							"text": "领用出库",
							"value": 2
						},
						{
							"text": "上报故障",
							"value": 3
						},
						{
							"text": "确认故障",
							"value": 4
						},
						{
							"text": "维修中",
							"value": 5
						},
						{
							"text": "已报废",
							"value": 6
						},
						{
							"text": "禁止使用",
							"value": 7
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				},
				storageRange: [],
				totalClassifyRange: [],
				classifyRange: [],
				firmRange: []
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			this.getRecord()
		},
		methods: {

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"storage_id,totalClassify_id,classify_id,firm_id,equipmentName,imgFile,equipmentParameter,useMethod,remark,storageState,equipmentStateInfo,purchaseTime,overInsuranceTime"
					).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data

					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			async getRecord() {
				//查询仓库信息
				await db.collection('tab_StorageInfo').field("storageName").get().then((res) => {
					const receivedData = res.result.data
					this.storageRange = receivedData.map(item => ({
						value: item._id,
						text: `${item.storageName}`
					}));
				}).catch((err) => {
					uni.showModal({
						content: err.message || '获取仓库信息失败',
						showCancel: false
					})
				})
			
				//查询装备总分类信息
				await db.collection('tab_EquipmentTotalClassify').field("totalKeyName,totalKeyValue").get().then((
					res) => {
					const receivedData = res.result.data
					this.totalClassifyRange = receivedData.map(item => ({
						value: item._id,
						text: `${item.totalKeyValue} _ ${item.totalKeyName}`
					}));
				}).catch((err) => {
					uni.showModal({
						content: err.message || '获取装备总分类失败',
						showCancel: false
					})
				})
			
				//查询装备分类信息
				await db.collection('tab_EquipmentClassify').field("classifyName,classifyNickName,directoryIndex")
					.get().then((res) => {
						const receivedData = res.result.data
						this.classifyRange = receivedData.map(item => ({
							value: item._id,
							text: `${item.classifyName} - 简称: ${item.classifyNickName} - 指导目录号: ${item.directoryIndex}`
						}));
					}).catch((err) => {
						uni.showModal({
							content: err.message || '获取装备分类失败',
							showCancel: false
						})
					})
			
				//查询设备厂商信息
				await db.collection('tab_EquipmentFirms').field("firmName").get().then((res) => {
					// console.log(res.result.data)
					const receivedData = res.result.data
					this.firmRange = receivedData.map(item => ({
						value: item._id,
						text: `${item.firmName}`
					}));
				}).catch((err) => {
					uni.showModal({
						content: err.message || '获取设备厂商信息失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>